﻿using System.Collections.Generic;
using System.IO;
using Fetches.Fetch.Dto;
using Fetches.Fetch.Utils;
using Newtonsoft.Json;

namespace Fetches.Fetch.Factory.Persistence
{
    //public  void RegisterWithHeartbeat(WorkshopServingInfo workshopInfo)
    //{
    //    //本地情况下,存在两种情况
    //    //如果本地有分配订单信息，就主动从文件中获得订单信息提交到自己的api
    //    //如果设置了主动突出的话当没有本地任务时，退出自己的api主动退出
    //    //如果不自动退出的话提供http api接受调用
    //}

    public class StandaloneRuntimeDataService : IRuntimeDataService
    {
        private string _runtimeDataPath;

        public StandaloneRuntimeDataService(string runtimeDataPath = "")
        {
            if (string.IsNullOrEmpty(runtimeDataPath))
            {
                runtimeDataPath = @"D:\Deploy\FetchRuntime";
            }
            _runtimeDataPath = runtimeDataPath;
            Directory.CreateDirectory(_runtimeDataPath);
            Directory.CreateDirectory(Path.Combine(_runtimeDataPath, "tasks"));
        }

        public static StandaloneRuntimeDataService Default()
        {
            return new StandaloneRuntimeDataService();
        }

        #region FactoryConfig

        public const string FactoryConfigFilePath = "FactoryConfig.json";

        public FactoryConfig ReadFactoryConfig()
        {
            var data = File.ReadAllText(FactoryConfigFilePath);
            return JsonConvert.DeserializeObject<FactoryConfig>(data);
        }

        public void WriteFactoryConfig(FactoryConfig config)
        {
            config.ToJsonFile(FactoryConfigFilePath);
        }

        public void Rebuild()
        {
            throw new System.NotImplementedException();
        }

        #endregion

        public IList<UnitSchedules> LoadAllUnitSchedules()
        {
            return new List<UnitSchedules>();
        }

        public void UpdateWorkshopScheduleData(UnitSchedules schedules)
        {
            //
        }

        public IList<FetchTask> LoadUnfinishedFetchTask()
        {
            var tasks = new List<FetchTask>();
            foreach (var tskFile in Directory.EnumerateFiles(Path.Combine(_runtimeDataPath, "tasks"), "*.tsk"))
            {
                tasks.Add(JsonFileHelper.FromFile<FetchTask>(tskFile));
            }

            return tasks;
        }

        public FetchTask GetFetchTaskByTaskId(long taskId)
        {
            var taskFile = GetTaskFilePath(taskId);
            return JsonFileHelper.FromFile<FetchTask>(taskFile);
        }

        public FetchTask GetFetchTaskByFetcherId(long fetcherId)
        {
            //本地模式下订单是提交到本机/api的，所以缓存中必然有FetchTask
            //本地模式也不会出现调整Fetcher的情况，所以除非逻辑问题否则绝对不会调用这个方法的
            throw new System.NotImplementedException();
        }

        public void RegisterOrUpdateFetchTask(FetchTask task)
        {
            var taskFile = GetTaskFilePath(task.Id);
            task.ToJsonFile(taskFile);
        }

        public void UpdateFetchTaskStatus(long taskId, FetchTaskStatus status)
        {
            if (status == FetchTaskStatus.Solved || status == FetchTaskStatus.Canceled)
            {
                var taskFile = GetTaskFilePath(taskId);
                File.Delete(taskFile);
            }
        }

        private string GetTaskFilePath(long taskId)
        {
            var taskFile = Path.Combine(_runtimeDataPath, "tasks", $"{taskId}.tsk");
            return taskFile;
        }
    }
}
